package com.wishu.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wishu.finance.domain.*;
import com.wishu.finance.enums.FinanceApplyStateEnum;
import com.wishu.finance.mapper.TCwPaymentPlanMapper;
import com.wishu.finance.mapper.TJrProductMapper;
import com.wishu.finance.mapper.TJrSfLoanMapper;
import com.wishu.finance.mapper.TSfContractMapper;
import com.wishu.finance.service.TJrSfLoanService;
import com.wishu.finance.utils.MyJinRongUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 25813
 * @description 针对表【t_jr_sf_loan(收房贷申请信息)】的数据库操作Service实现
 * @createDate 2023-04-28 10:57:26
 */
@Service
public class TJrSfLoanServiceImpl extends ServiceImpl<TJrSfLoanMapper, TJrSfLoan>
        implements TJrSfLoanService {

    @Resource
    TJrProductMapper tJrProductMapper;

    @Resource
    TSfContractMapper tSfContractMapper;

    @Resource
    TCwPaymentPlanMapper tCwPaymentPlanMapper;

    @Resource
    TJrSfLoanMapper tJrSfLoanMapper;


    @Override
    public SearchSfLoanDetailsResponseDto getSfLoanDetail(SearchSfLoanDetailRequestDto sfdto) {
        SearchSfLoanDetailsResponseDto dto = new SearchSfLoanDetailsResponseDto();
        List<SearchSfLoanDetailMiniResponseDto> spList = new ArrayList<SearchSfLoanDetailMiniResponseDto>();
        TJrProduct product = tJrProductMapper.selectById(sfdto.getProductId());
        //授信率
        Double creditLine = MyJinRongUtils.div(product.getCreditLine().doubleValue(), 100, 2);
        //一次性服务费
        double serviceFee = MyJinRongUtils.div(Double.parseDouble(sfdto.getServiceFee()), 100, 4);
        //利率
        double rate = MyJinRongUtils.div(Double.parseDouble(sfdto.getRate()), 100, 4);// 利率

        //授信额合计
        double sxBalance = MyJinRongUtils.mul(sfdto.getBalance(), creditLine);

        // 合同期数
        Long sfperiod = sfdto.getPeriods();
        int sfperiods = sfperiod.intValue();

        //服务费合计=   (借款金额*一次性服务费 /12 * 期数 * 授信额)
        double ser_Charge = MyJinRongUtils.mul(sfdto.getBalance(), serviceFee);
        double ser_Charge_ = MyJinRongUtils.div(ser_Charge, 12, 2);
        double _ser_Charge = MyJinRongUtils.mul(ser_Charge_, sfperiods);
        double serCharge = MyJinRongUtils.mul(_ser_Charge, creditLine);

        // 计算 月租金
        double month_RateAmount = MyJinRongUtils.div(sfdto.getBalance(), sfperiods, 2);
        // 借款总额(应付租约合计 )   = 月租金* 期数 * 授信
        double monthAmount = MyJinRongUtils.mul(month_RateAmount, sfperiods);
        double payAbleCount_ = MyJinRongUtils.mul(monthAmount, creditLine);

        // 计算收房贷利息合计= 借款金额* 利率/12  * 授信额 * 期数
        //借款金额* 利率
        double rates = MyJinRongUtils.mul(payAbleCount_, rate);
        // 利率/12
        double monthRateAmounts_ = MyJinRongUtils.div(rates, 12, 2);
        double monthRateAmounts = MyJinRongUtils.mul(monthRateAmounts_, sfperiods);

        //利息合计 InterestCount
        double InterestCount = 0;
        //还款总额合计      (账期还款金额的合计)
        double rePaymentCount = 0;
        //应付租约合计      (总金额)
        double payAbleCount = payAbleCount_;
        // 根据一段时间区间，按月份拆分成多个时间段
        List<MyJinRongUtils.KeyValueForDate> splitMonth = MyJinRongUtils.getSplitMonthForDate(sfdto.getStartDate(), sfdto.getEndDate());
        //收房合同
        TSfContract sfentity = tSfContractMapper.selectById(sfdto.getContractId());
        int no = 1;

        SearchSfLoanDetailMiniResponseDto sfdmini = null;
        // 账期利息 （每月利息）= 利息总和/ 期数
        double rateAmount = MyJinRongUtils.div(monthRateAmounts, sfperiods, 2);
        //计算月租金
        // 账期还款金额（每月账期还款金）= 还款总额合计 / 期数
        double repaymentAmount_ = MyJinRongUtils.div(payAbleCount, sfperiods, 2);
        double repaymentAmount = MyJinRongUtils.add(repaymentAmount_, rateAmount);
        //利息合计
        InterestCount = MyJinRongUtils.add(InterestCount, monthRateAmounts);
        // 还款总额合计  = 账期还款金额（每月账期还款金）* 期数
        rePaymentCount = MyJinRongUtils.mul(repaymentAmount, sfperiods);
        // 循环计算分期详情列表
        for (MyJinRongUtils.KeyValueForDate v : splitMonth) {
            sfdmini = new SearchSfLoanDetailMiniResponseDto();
            sfdmini.setNo(no);
            // 房产编号
            sfdmini.setRoomCode(sfentity.getHouseId());
            // 房产信息 = 小区名+房产信息
            sfdmini.setRealEstateInfo(sfentity.getPremiseName() + sfentity.getHouseName());
            // 利息
            sfdmini.setMonthRateAmount(rateAmount);
            // 月租金
            sfdmini.setMonthRepaymentAmount(repaymentAmount);
            // 合同开始日
            sfdmini.setStarLoanday(v.getStartDate());
            // 合同结束日
            sfdmini.setEndLoanday(v.getEndDate());
            spList.add(sfdmini);
            no++;
        }
        dto.setPayAbleCount(payAbleCount + "");// 应付租约合计
        dto.setRePaymentCount(rePaymentCount + "");// 还款总额合计
        dto.setInterestCount(InterestCount + "");// 收房贷利息合计
        dto.setSerCharge(serCharge + "");// 一次性服务费
        dto.setProductId(product.getId());//产品id
        dto.setSxAbleCount(sxBalance + "");
        dto.setSfLoan(spList);
        dto.setId(sfdto.getContractId());//合同id

        dto.setServiceFee(sfdto.getServiceFee());//一次性服务费率
        dto.setRate(sfdto.getRate());//利率

        return dto;
    }

    @Override
    public JrSfLoanDetailsResponseDto selectSfLoanDetails(Long id) {
        return baseMapper.selectSfLoanDetails(id);
    }

    @Override
    public void saveLoan(SaveSfLoanForm sfdto) {
        //保存收房贷申请
        TJrSfLoan jrse = new TJrSfLoan();
        jrse.setBusinessId(131L);
        jrse.setDeptId(169L);
        jrse.setDeptNo("");
        jrse.setSfContractId(sfdto.getId());
        jrse.setLoanAmount(sfdto.getSxBalance());
        jrse.setMonthLimit(sfdto.getPeriods());
        jrse.setRate(sfdto.getRate());
        jrse.setServiceFee(sfdto.getServiceFee());
        jrse.setJrProductId(sfdto.getProductId());
        jrse.setReLeaseCount(sfdto.getPayAbleCount());
        jrse.setRpAmountCount(sfdto.getRePaymentCount());
        jrse.setSerCharge(sfdto.getSerCharge());
        jrse.setAgInterestRate(sfdto.getInterestCount());
        jrse.setApplyState(FinanceApplyStateEnum.SHZ.getIndex());
        jrse.setRemark(sfdto.getRemarks());
        jrse.setCreateUserid(1L);
        jrse.setCreateTime(new Date());
        jrse.setUpdateUserid(1L);
        jrse.setUpdateTime(new Date());
        jrse.setDelFlg(0);
        jrse.setSfLoanOrderNo("SFD201806081000052639");
        baseMapper.insert(jrse);
    }

}




